<template>
  <gui-page ref="guiPage" :customHeader="true">
    <template v-slot:gHeader>
      <nav-bar-custom left-icon="left" :title="$t('multilingual.inventoryDetails')"></nav-bar-custom>
    </template>
    <template v-slot:gBody>
      <view class="distributed">
        <!-- 调拨单信息 -->
        <view class="custom-form-card" v-if="data.billCodeInfo">
          <view class="custom-card-title">
            <text class="title-line"></text>
            {{ $t('multilingual.inventoryInformation') }}
          </view>
          <view class="custom-card-itemOne">
            <text class="item-info-title">{{ $t('finishedInventory.inventoryNumber') }}：</text>
            {{ data.billCodeInfo.billCode }}
          </view>
          <view class="custom-card-itemOne addflex">
            <text class="item-info-title itemflex">{{ $t('pageTranslation.stocktakingWarehouse') }}：
              <text style="color: #333;">{{ data.billCodeInfo.warehouseName }}</text>

            </text>
            <text class="item-info-title itemflex">{{ $t('pageTranslation.compiler') }}：
              <text style="color: #333;">{{ data.billCodeInfo.createUserName }}</text>
            </text>
          </view>

          <!--<view class="custom-card-itemOne addflex">-->

          <!--</view>-->
          <view class="custom-card-itemOne addflex">
            <text class="item-info-title itemflex">{{ $t('pageTranslation.countOfItem') }}：
              <text style="color: #333;">{{ data.billCodeInfo.materialSum }}</text>
            </text>
            <text class="item-info-title itemflex">{{ $t('pageTranslation.amountOfInventory') }}：
              <text style="color: #333;">{{ data.billCodeInfo.stockQtySum }}</text>
            </text>
          </view>
          <view class="custom-card-itemOne addflex">
            <text class="item-info-title itemflex">{{ $t('pageTranslation.totalQtyThat') }}：
              <text style="color: #333;">{{ data.billCodeInfo.waitQtySum >= 0 ? data.billCodeInfo.waitQtySum : 0
                }}</text>
            </text>
            <text class="item-info-title itemflex">{{ $t('pageTranslation.totalQtyOfScanned') }}：
              <text style="color: #333;">{{ data.billCodeInfo.checkQtySum }}</text>
            </text>
          </view>
          <view class="custom-card-itemOne ">
            <text class="item-info-title itemflex">{{ $t('translationImage.documentationDate') }}：
              <text style="color: #333;"> {{ data.billCodeInfo.creationTime }}</text>
            </text>

          </view>
        </view>
        <!-- 扫描条码 -->
        <view class="custom-form-card">
          <view class="custom-card-title">
            <text class="title-line"></text>
            {{ $t('distributedEnter.barcodeScan') }}
          </view>
          <view class="custom-card-scan">
            <uni-easyinput class="uni-mt-5" suffixIcon="scan" v-model="data.scanValue"
              :placeholder="$t('stockManage.pleaseScanCode')" @confirm="confirm" @iconClick="iconClick">
            </uni-easyinput>
          </view>
        </view>
        <!-- 底部显示区域 -->
        <scroll-view :show-scrollbar="false" :scroll-y="true" class="scroll">
          <!-- 当前扫描条码 -->
          <view v-if="data.checkInfo" class="custom-form-card">
            <uni-collapse v-model="data.value">
              <uni-collapse-item titleBorder="none" :show-animation="true">
                <template v-slot:title>
                  <view class="custom-card-title">
                    <text class="title-line"></text>
                    {{ $t('distributedOut.atPresent') }}
                  </view>
                </template>
                <view class="content">
                  <view class="custom-card-itemOne">
                    <text class="item-info-title">{{ $t('distributedOut.barcode') }}：</text>
                    {{ data.checkInfo.barcode }}
                  </view>
                  <view class="custom-card-itemOne">
                    <text class="item-info-title">{{ $t('distributedEnter.materialCode') }}：</text>
                    {{ data.checkInfo.materialCode }}
                  </view>
                  <view class="custom-card-itemOne">
                    <text class="item-info-title">{{ $t('distributedEnter.materialName') }}：</text>
                    {{ data.checkInfo.materialName }}
                  </view>
                  <view class="custom-card-itemOne">
                    <text class="item-info-title">{{ $t('distributedEnter.materialSpec') }}：</text>
                    {{ data.checkInfo.materialSpec }}
                  </view>
                  <view class="custom-card-itemOne">
                    <text class="item-info-title">{{ $t('stockManage.materialUnit') }}：</text>
                    {{ data.checkInfo.unit }}
                  </view>
                  <view class="custom-card-itemOne">
                    <text class="item-info-title">{{ $t('translationImage.currentWarehouse') }}：</text>
                    {{ data.checkInfo.warehouseName }}
                  </view>
                  <view class="custom-card-itemOne">
                    <text class="item-info-title">{{ $t('translationImage.currentLocation') }}：</text>
                    {{ data.checkInfo.locationCode }}
                  </view>
                  <view class="custom-card-itemOne">
                    <text class="item-info-title">{{ $t('pageTranslation.qtyOfDelivery')}}：</text>
                    {{ data.checkInfo.barcodeStockQty }}
                  </view>
                  <view class="custom-card-itemOne">
                    <text class="item-info-title">{{ $t('pageTranslation.thisCheckQty') }}：</text>
                    <uni-tag type="primary" :text="data.checkInfo.barcodeCheckQty"/>
                    <!--{{ data.checkInfo.barcodeCheckQty }}-->
                  </view>
                  <!--<view class="custom-card-itemOne">-->
                  <!--  <text class="item-info-title">{{ $t('JsInternational.ofStocktaked') }}：</text>-->
                  <!--  {{ data.checkInfo.checkQty }}-->
                  <!--</view>-->
                  <!--<view class="custom-card-itemOne">-->
                  <!--  <text class="item-info-title">{{ $t('JsInternational.notStocktaking') }}：</text>-->
                  <!--  {{ data.checkInfo.notCheckQty >= 0 ? data.checkInfo.notCheckQty : 0 }}-->
                  <!--</view>-->
                  <!--<view class="custom-card-itemOne">-->
                  <!--  <text class="item-info-title">{{ $t('JsInternational.ofStock') }}：</text>-->
                  <!--  {{ data.checkInfo.stockQty }}-->
                  <!--</view>-->
                </view>
              </uni-collapse-item>
            </uni-collapse>
          </view>
          <view style="height:100rpx"></view>
        </scroll-view>
        <!-- 底部操作栏 -->
        <view class="page-bottom-boxtwo">
          <view class="page-bottomBtn bottomBtn-bgcolor-green" @click="handelCheckRecord">
            {{ $t('pageTranslation.checkTheRecords') }}
          </view>
          <view class="page-bottomBtn bottomBtn-bgcolor-green" @click="handelCheck" v-if="permission(['auditBtn'])">
            {{ $t('pageTranslation.approve') }}
          </view>
        </view>
      </view>
      <!-- 页面弹窗 -->
      <uni-popup ref="inputDialog" type="center" :mask-click="false">
        <view v-if="data.scanInfo" class="input-dialog-box">
          <view class="input-dialog-content">
            <view class="input-dialog-itembox">
              <view class="input-dialog-item">
                <text style="color:red;width:300rpx">{{ $t('pageTranslation.realInventoryQtyNew') }}：</text><input
                  class="input" type="number" style="color:red" v-model="data.scanInfo.checkNum"
                  :placeholder="$t('pageTranslation.plsRealInventoryQty')" />
              </view>
            </view>
            <view v-if="data.remarkBool" class="input-dialog-item addborder">
              <textarea class="textarea" :maxlength="-1" v-model="data.scanInfo.remarkText"
                placeholder-style="color:#F76260" :placeholder="$t('pageTranslation.PlsInputRemarks')" />
            </view>
            <view class="input-dialog-itembox">
              <view class="input-dialog-item">
                {{ $t('pageTranslation.chekStatus') }}：{{ data.scanInfo.ckeckFlag == "Y" ? "check" : "unCheck" }}
              </view>
              <view class="input-dialog-item">
                {{ $t('distributedOut.barcode') }}：{{ data.scanInfo.barcode }}
              </view>
              <view class="input-dialog-item">
                {{ $t('distributedEnter.materialCode') }}：{{ data.scanInfo.materialCode }}
              </view>
              <view class="input-dialog-item">
                {{ $t('distributedEnter.materialName') }}：{{ data.scanInfo.materialName }}
              </view>
              <view class="input-dialog-item">
                {{ $t('distributedEnter.materialSpec') }}：{{ data.scanInfo.materialSpec }}
              </view>
              <view class="input-dialog-item">
                {{ $t('distributedEnter.uom') }}：{{ data.scanInfo.unit }}
              </view>
              <view class="input-dialog-item">
                {{ $t('distributedEnter.materialName') }}：{{ data.scanInfo.materialName }}
              </view>
              <!-- [[2022-10-27 SJM 改 -->
              <view class="input-dialog-item">
                {{ $t('pageTranslation.barcodeQty') }}：{{ data.scanInfo.stockQty }}<!-- {{data.scanInfo.currentQty}} -->
              </view>
              <view class="input-dialog-item">
                {{ $t('pageTranslation.checkQty') }}：

                <!--<uni-tag type="primary" :text="data.scanInfo.checkQty"></uni-tag>-->
                 {{data.scanInfo.checkQty}}
              </view>
              <!-- <view class="input-dialog-item">
                {{$t('pageTranslation.barcodeStatus')}}：{{data.scanInfo.barcodeStatus}}
              </view> -->
              <!-- 2022-10-27 SJM 改 ]] -->
            </view>
          </view>
          <view class="input-dialog-footer">
            <view class="input-dialog-button" @click="cancelFn">
              {{ $t('calendar.cancel') }}
            </view>
            <view class="input-dialog-button dialog-button-left" @click="scanConfirmFn">
              {{ $t('calendar.confirm') }}
            </view>
          </view>
        </view>
      </uni-popup>
    </template>
  </gui-page>
</template>

<script setup>
import { navigate, navigateBack } from '@/utils/routerSkip.js'
import pdaScan from '@/hooks/pdaScan.js'
import { findStartCheckStockDetail, selectWmsCheckstockDByBarcodeAndCheckStockId, checkStockCommit } from '@/api/api.js'
import { TEST_URL, PROD_URL, IMG_BASE_URL } from '@/constant/config.js'
import {TOKEN} from '@/constant/index.js'
import { ref,reactive,toRaw, watch, computed, onMounted} from 'vue'
import { useStore } from 'vuex'
import { basPdaOperationLogFn } from '@/utils/index.js';
import { OPERATION_COMMIT, OPERATION_SCAN, OPERATION_CHECK_CODE } from '@/constant/index.js'
import { getDataDictionaryFn, base64toFile } from '@/utils/index.js'

//JS国际化引入
import { useI18n } from 'vue-i18n'
import UniTag from "../../uni_modules/uni-tag/components/uni-tag/uni-tag.vue";

const { t } = useI18n()

const { scan } = pdaScan()
let store = useStore()
// 接受来自父组件的传参 页面传值
const props = defineProps({
  id: String
})
let inputDialog = ref(null)
let data = reactive({
  billCodeInfo: undefined,// 盘点信息
  id: props.id,// 上级界面传过来的id
  scanInfo: undefined,
  currentScanInfo: undefined,// 当前扫描信息
  scanValue: '',// 扫描的条码号
  value: ['0'],
  remarkBool: false,// 备注bool
  formData: '',// 签名信息
  checkFinishList: [],
  checkInfo: undefined,// 请求返回盘点数据
  focus: false

})
// 签名信息
data.formData = computed(() => {
  return store.state.fromData
})
// remarkBool 标示当前是否需要备注
data.remarkBool = computed(() => {
  if (!data.scanInfo) {
    return false
  } else {
    // return Number((data.scanInfo.checkNum || 0 )) != Number(data.scanInfo.currentQty) ? true :false
    return Number((data.scanInfo.checkNum || 0)) != Number(data.scanInfo.stockQty) ? true : false
  }
})
onMounted(() => {
  console.log('开始监听PDA扫码')
  uni.$on('scancodedate', (data) => {
    console.log('获取到的code：' + data.code)
    getCode(data.code, 'pda')
  })
  getRequestData()
})
// 当前扫描信息关闭  清除当前扫描的信息
const cancelFn = () => {
  data.scanInfo = undefined
  data.focus = false
  inputDialog.value.close()
}
// 用户调起相机扫码
const iconClick = async (type) => {
  console.log(type)
  if (type === 'suffix') {
    let code = await scan()
    getCode(code, 'scan')
  }
}
// 用户点击键盘上搜索
const confirm = () => {
  getCode(data.scanValue, 'keydown')
}
// 获取code
const getCode = (code, type) => {
  // 判断这个托盘本次有没有绑定过
  // let scanInfo = {
  // 	checkNum:100,
  // 	remarkText:'',
  // 	barcode:'123123123123',
  // 	materialCode:'123321312',
  // 	materialName:'物料名称',
  // 	materialSpec:'',
  // 	unit:'',
  // 	materialName:'',
  // 	currentQty:100,
  // 	barcodeStatus:'',
  // }
  // data.scanInfo = scanInfo
  // inputDialog.value.open()
  // return
  data.scanValue = code
  let parmes = {
    barcode: code,
    // selectType: 'checkStock',
    checkStockId: data.id
  }
  selectWmsCheckstockDByBarcodeAndCheckStockId(parmes).then(res => {
    console.log(res)
    try {
      let inputParameter = JSON.stringify(parmes)
      let returnParameter = JSON.stringify(res)
      let operationPicture = '盘点'
      let callInterface = res.rquestUrl
      let opertionParmes = {
        inputParameter,
        returnParameter,
        operationPicture,
        callInterface,
        responseCode: res.code,//返回状态
        errorMessage: res.msg,//错误信息
        isPass: res.code == 0 ? 'Y' : 'N',//是否成功 Y N
        operationType: OPERATION_SCAN,
				module: 'WMS',
				source: "PDA",
      }
      basPdaOperationLogFn(opertionParmes)
    } catch (error) {
    }
    if (res.code == 0) {
      data.scanInfo = res.data
      /* data.scanInfo.checkNum = data.scanInfo.currentQty// 初始化实盘数量 */
      data.scanInfo.checkNum = data.scanInfo.checkQty > 0 ? data.scanInfo.checkQty : data.scanInfo.stockQty// 初始化实盘数量
      data.scanInfo.remarkText = '' // 初始化实盘数量
      data.focus = true
      inputDialog.value.open()
    } else {
      uni.showToast({ title: res.msg, icon: 'none' })
    }
  })
}
// 查看记录
const handelCheckRecord = () => {
  navigate({
    url: `/pages/check/checkRecord?id=${data.id}`
  })
}
// 查询初始化数据
const getRequestData = () => {
  let parmes = {
    id: data.id
  }
  findStartCheckStockDetail(parmes).then(res => {
    if (res.code == 0) {
      data.billCodeInfo = res.data
      // watcShowscanList() // 去手动调取计算监属性
    }
  })
}
// 扫码弹框确认信息
const scanConfirmFn = () => {
  if (!data.scanInfo.checkNum) {
    uni.showToast({
      title: t('pageTranslation.plsRealInventoryQty'),
      icon: 'none'
    })
    return
  }
  if (Number(data.scanInfo.checkNum) < 0) {
    uni.showToast({
      title: t('pageTranslation.realInventoryQtyLess'),
      icon: 'none'
    })
    return
  }
  if (data.remarkBool && !data.scanInfo.remarkText.length) {
    uni.showToast({
      title: t('pageTranslation.PlsInputRemarks'),
      icon: 'none'
    })
    return
  }
  let parmes = {
    id: data.id,
    barcodeId: data.scanInfo.barcodeId, // 条码id
    barcode: data.scanInfo.barcode, // 条码
    checkQty: data.scanInfo.checkNum,
    batchNumber: data.scanInfo.batchNumber,
    remark: data.scanInfo.remarkText
  }
  checkStockCommit(parmes).then(res => {
    console.log(res)
    try {
      let inputParameter = JSON.stringify(parmes)
      let returnParameter = JSON.stringify(res)
      let operationPicture = '盘点'
      let callInterface = res.rquestUrl
      let opertionParmes = {
        inputParameter,
        returnParameter,
        operationPicture,
        callInterface,
        responseCode: res.code,//返回状态
        errorMessage: res.msg,//错误信息
        isPass: res.code == 0 ? 'Y' : 'N',//是否成功 Y N
        operationType: OPERATION_CHECK_CODE,
				module: 'WMS',
				source: "PDA",
      }
      basPdaOperationLogFn(opertionParmes)
    } catch (error) {
    }
    if (res.code == 0) {
      data.checkInfo = res.data
      data.checkInfo.barcode = data.scanValue
      getRequestData()
      //重新调用接口
    } else {
      uni.showToast({ title: res.msg, icon: 'none' })
    }
  })
  data.focus = false
  inputDialog.value.close()
}
// 审核接口
const handelCheck = async () => {
  // 盘点审核检验当前用户是否有审核资格
  let bool = await store.dispatch('checkUser')
  if (!bool) {
    uni.showToast({
      title: t('JsInternational.sorryAuthority'),
      icon: 'none'
    })
    return
  }
  if (!data.formData.length) {
    navigate({
      url: `/pages/check/signature?id=${data.id}`
    })
  }
  // uploadFileMethod()
}

// 上传图片获取开始上传
// const uploadFileMethod = () => {
//   let isDev = process.env.NODE_ENV === 'development'
//   let baseUrl = isDev ? TEST_URL : PROD_URL
//   let token = uni.getStorageSync(TOKEN)
//   let str = base64toFile(data.formData, 'file')
//   let formData = {
//     bizId: data.id,
//     file: str,
//     bizType: 'wms_checkstock_h'
//   }
//   console.log(formData)
//   // return
//   uni.showLoading({
//     title: t('JsInternational.uploading')
//   })
//   // 调用uni 上传图片方法
//   uni.uploadFile({
//     url: baseUrl + '/system/oss/oss-simple', //上传接口
//     name: 'file',
// 		header: {

// 			'token': token
// 		},
//     formData: formData,
//     success: (uploadFileRes) => {
//       uni.hideLoading()
//       const back = JSON.parse(uploadFileRes.data)
//       try {
//         let inputParameter = JSON.stringify(formData)
//         let returnParameter = JSON.stringify(uploadFileRes)
//         let operationPicture = '盘点'
//         let callInterface = baseUrl + '/system/oss/oss-simple'
//         let opertionParmes = {
//           inputParameter,
//           returnParameter,
//           operationPicture,
//           callInterface,
//           responseCode:uploadFileRes.statusCode,//返回状态
//           errorMessage:back.msg,//错误信息
//           isPass:back.statusCode == 200 == 200 ? 'Y' : 'N',//是否成功 Y N
//           operationType:'图片上传'
//         }
//         basPdaOperationLogFn(opertionParmes)
//       } catch (error) {
//       }
//       if (back.statusCode == 200) {
//         let imgPath = back.data;
//         // let imgPath = IMG_BASE_URL + back.filePath
//         checkRequest(imgPath)
//       } else {
//         uni.showToast({title:back.message, icon:"none"});
//       }
//     },
//     fail: () => {
//       uni.hideLoading()
//       uni.showToast(t('JsInternational.pictureUploading'))
// 	  try {
// 		let inputParameter = '无'
// 		let returnParameter = '无'
// 		let operationPicture = '盘点'
// 		let callInterface = baseUrl + '/system/oss/oss-simple'
// 		let opertionParmes = {
// 			inputParameter,
// 			returnParameter,
// 			operationPicture,
// 			callInterface,
// 			responseCode:'无',//返回状态
// 			errorMessage:'上传失败',//错误信息
// 			isPass:'N',//是否成功 Y N
// 			operationType:'图片上传'
// 		}
// 		basPdaOperationLogFn(opertionParmes)
// 	} catch (error) {
// 	}
//     },
//     complete: function () {
//       uni.hideLoading()
//     }
//   })
// }
// 审核
// const checkRequest = (imgPath) => {
//   let parmes = {
//     id: data.id, // 收料单id
//     auditSign: imgPath
//   }
//   checkStockAudit(parmes).then(res => {
//     console.log(res)
// 	try {
// 		let inputParameter = JSON.stringify(parmes)
// 		let returnParameter = JSON.stringify(res)
// 		let operationPicture = '盘点'
// 		let callInterface = res.rquestUrl
// 		let opertionParmes = {
// 			inputParameter,
// 			returnParameter,
// 			operationPicture,
// 			callInterface,
// 			responseCode:res.status,//返回状态
// 			errorMessage:res.message,//错误信息
// 			isPass:res.status == 200 ? 'Y' : 'N',//是否成功 Y N
// 			operationType:OPERATION_COMMIT
// 		}
// 		basPdaOperationLogFn(opertionParmes)
// 	} catch (error) {
// 	}
//     if (res.status == 200) {
//       uni.showToast({
//         title: t('smashRemoval.submitSuccessfully'),
//         icon: 'none',
//         complete: () => {
//           //清除 缓存总store签名信息
//           store.commit('delFormData')
//           navigateBack()
//         }
//       })
//     } else {
//       uni.showToast({ title: res.message, icon: 'none' })
//     }
//   })
// }
</script>

<style lang="scss" scoped>
.card-my {
  display: flex;
  flex-direction: column;
}

.addflex {
  display: flex;
  align-items: center;

  .itemflex {
    flex: 1;
  }
}

.distributed {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 200rpx);
  // height: 100vh;
}

.scroll {
  margin-top: 15rpx;
  flex: 1;
  height: 2rpx;
}

.page-bottom-box {
  position: fixed;
}

.addborder {
  border: 1rpx solid #DCDFE6;
  box-sizing: border-box;
  padding: 15rpx;
  margin-bottom: 15rpx;
  border-radius: 8rpx;
}

.input-dialog-itembox {
  padding: 15rpx;
  box-sizing: border-box;
  border: 1rpx solid #DCDFE6;
  margin-bottom: 15rpx;
  border-radius: 8rpx;
}

.input-dialog-item {
  font-size: 24rpx;
}

.input,
.textarea {
  font-size: 24rpx;
}
</style>
